package web

import (
	"gitee.com/dayu1985/framework/logging"

	"github.com/gin-gonic/gin"
	"gopkg.in/mgo.v2/bson"
)

const (
	ERRONO_SUCCESS = 0    //服务正常
	ERRONO_ANY     = 9999 //服务错误
)

func Result(ctx *gin.Context, result interface{}, err error) {

	if err != nil {
		Fail(ctx, err.Error(), err)
		return
	}

	Success(ctx, result)
}

func Success(ctx *gin.Context, result interface{}) {

	ctx.JSON(200, bson.M{
		"Code":     ERRONO_SUCCESS,
		"Message":  "",
		"Response": result,
	})
}

func Bad(ctx *gin.Context, errno int, message string) {

	ctx.JSON(200, bson.M{
		"Code":     errno,
		"Message":  message,
		"Response": nil,
	})

	ctx.Writer.WriteHeaderNow()
	ctx.Abort()
}

func Fail(ctx *gin.Context, message interface{}, err error) {

	if err != nil {
		logging.Error("%v", message)
		logging.Error(err.Error())
	}

	ctx.JSON(200, bson.M{
		"Code":     9999,
		"Message":  "service unavailable",
		"Response": nil,
	})

	ctx.Writer.WriteHeaderNow()
	ctx.Abort()
}

func Abort(ctx *gin.Context, status int, message string, errs ...error) {

	var err error

	if len(errs) > 0 {
		err = errs[0]
	}

	if err != nil {
		logging.Error("%s %v", message, err)
	}

	ctx.JSON(200, bson.M{
		"Code":     status,
		"Message":  message,
		"Response": nil,
	})

	ctx.Writer.WriteHeaderNow()
	ctx.Abort()
}
